package org.example.Servlet.PersonServlet;

import org.example.Dao.PersonDao;
import org.example.Dao.TopicDao;
import org.example.entity.Person;
import org.example.entity.Topic;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
        PersonDao personDao = new PersonDao();
        TopicDao topicDao = new TopicDao();
        try {
            Person person = personDao.login(email, password);
            // 用户不存在
            if (person == null) {
                session.setAttribute("loginMessage", "账号密码错误");
                req.getRequestDispatcher("/views/login.jsp").forward(req, resp);
            }
            //用户存在判断是管理员还是普通用户，分别跳转到不同登录页面
            // level 为1是管理员，0是普通用户
            session.setAttribute("person", person);
            session.setAttribute("loginMessage", "");
            session.setAttribute("registerMessage", "");
            System.out.println(person.toString());

            if (person.getLevel() == 0) {
                //跳转到普通用户页面
                resp.sendRedirect(req.getContextPath() + "/person/index");
            } else {
                //跳转到管理员页面
                resp.sendRedirect(req.getContextPath() + "/admin/index");
            }
        } catch (Exception e) {
            System.out.println("error ==> " + e.getMessage());
            session.setAttribute("loginMessage", "服务器维护中");
            req.getRequestDispatcher("/views/login.jsp").forward(req, resp);
        }

    }
}
